package com.gz.moreaseManager.sys.service.impl;

import com.gz.moreaseManager.sys.entity.Menu;
import com.gz.moreaseManager.sys.entity.Role;
import com.gz.moreaseManager.sys.mapper.MenuMapper;
import com.gz.moreaseManager.sys.mapper.UserRoleMapper;
import com.gz.moreaseManager.sys.service.IMenuService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单信息表 服务实现类
 * </p>
 *
 * @author wike
 * @since 2019-02-19
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public List<Menu> findMenuListByUserId(Integer userId, Byte menuType, Byte status) {

        //判断用户是否有系统管理员角色
        List<Role> roleList = userRoleMapper.findRoleListByUserId( userId );
        boolean superFlag = false;
        for(Role role: roleList){
            if( role.getRoleId().equals(1)){//超级管理员
                superFlag = true;
                break;
            }
        }
        List<Menu> menus;
        if( superFlag ){
            menus = menuMapper.findManagerMenuList(userId,menuType,status);
        }else{
            menus = menuMapper.findMenuListByUserId(userId,menuType,status);
        }
        List<Menu> menuList = packingMenus("0",menus);
        return menuList;
    }

    @Override
    public List<Menu> findMenuListByRoleId(Integer roleId) {
        List<Menu> menuList = menuMapper.findMenuListByRoleId( roleId );
        return menuList;
    }

    /**
     * 递归打包菜单
     *
     * @param parentCode   父菜单编码
     * @param sourceMenu 用户权限
     * @return 菜单结构集
     */
    private List<Menu> packingMenus(String parentCode, List<Menu> sourceMenu) {
        List<Menu> remainMenu, menuList = new ArrayList<>();
        remainMenu = new ArrayList<>(sourceMenu);
        for (Menu menuInfo : sourceMenu) {
            if (parentCode.equals(menuInfo.getParentCode())) {
                remainMenu.remove(menuInfo);
                menuInfo.setChildren(packingMenus(menuInfo.getMenuCode(), remainMenu));
                menuList.add(menuInfo);
            }
        }
        return menuList;
    }
}
